package sdufe.lele.controller;


import org.apache.shiro.util.ThreadContext;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import sdufe.lele.annotation.authToken;
import sdufe.lele.dao.UserinfoMapper;
import sdufe.lele.model.Userinfo;
import sdufe.lele.result.ApiResult;
import sdufe.lele.result.MapResult;
import sdufe.lele.result.Result;
import sdufe.lele.service.RedisDateTimeService;
import sdufe.lele.uitl.Constant;
import sdufe.lele.uitl.Token;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * Created by zhnh9 on 4/9/2017.
 */
@RestController
@RequestMapping("/myinfo")

public class MyInfoController {
    @Resource
    private UserinfoMapper userinfoMapper;

    @Resource
    private RedisDateTimeService redisDateTimeService;



    @RequestMapping("/init.do")
    @authToken
    public Result getMyInfo() {
        MapResult mapResult = new MapResult();
        Userinfo userinfo = userinfoMapper.selectByPhone((String) ThreadContext.get("user-phone"));
        mapResult.put("userName", userinfo.getUsername());
        mapResult.put("userAge", userinfo.getUserage());
        mapResult.put("userPhone", userinfo.getUsertele());
        mapResult.put("userEmail", userinfo.getUseremail());
        return mapResult;

    }

    @RequestMapping("/update.do")
    @authToken
    public Result updateMyInfo(@RequestParam(name = "userage") String userage,
                               @RequestParam(name = "password") String password,
                               @RequestParam(name = "useremail") String useremail,
                               @RequestParam(name = "userphone") String userphone
    ) {

        Userinfo userinfo = new Userinfo();
        MapResult mapResult = new MapResult();
        String old_phone = (String) ThreadContext.get("user-phone");//这一步是为了拿到userId
        Userinfo user = userinfoMapper.selectByPhone(old_phone);
        userinfo.setUserid(user.getUserid());//必须有userId，update依靠userId来更新数据库
        userinfo.setUserage(userage);
        userinfo.setUseremail(useremail);
        userinfo.setUserpassword(password);
        userinfo.setUsertele(userphone);
        userinfoMapper.updateByPrimaryKeySelective(userinfo);
        mapResult.put("token", Token.createToken("userphone",userphone,"rem-pass",password));
        redisDateTimeService.setByKey(userphone, LocalDateTime.now());
        redisDateTimeService.deleteByKey(old_phone);


        return mapResult;

    }
}
